import socket from 'socket.io-client';
import { MessageBox } from 'element-ui';
import axios from './axios';

let chatIO = null;
// eslint-disable-next-line
export const initChat = (store) => {
  if (chatIO) return Promise.resolve(chatIO);
  const chat = socket.connect('ws://192.168.137.35:8080/chat');

  return new Promise((resolve) => {
    chat.on('connect', () => {
      chat.emit('join', {
        token: window.localStorage.getItem('__token__'),
      });

      chat.on('ok', () => {
        chatIO = chat;
        resolve(chatIO);
      });
    });
  });
};

let notifyIO = null;
// eslint-disable-next-line
export const initNotify = (store) => {
  if (notifyIO) return Promise.resolve(notifyIO);
  const notify = socket.connect('ws://192.168.137.35:8080/notify');

  return new Promise((resolve) => {
    notify.on('connect', () => {
      notify.emit('join', {
        token: window.localStorage.getItem('__token__'),
      });

      notify.on('ok', () => {
        notifyIO = notify;
        resolve(notifyIO);
      });

      notify.on('message', (data) => {
        const { user, relation } = data.data;

        MessageBox.confirm(`${user.nickname || user.username}想要添加你为好友`).then(() => {
          axios.post('/api/friend/confirm', { relationID: relation.id });
        });
      });
    });
  });
};

export default { initChat, initNotify };
